﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Text;
using System.Text.RegularExpressions;

namespace fanfu.Common
{
    /// <summary>
    /// SQL注入攻击的安全防范方法类
    /// </summary>
    public sealed class SafeSql
    {
        private const string StrKeyWord = @"select|insert|delete|from|count(|drop table|update|truncate|asc(|mid(|char(|xp_cmdshell|exec master|netlocalgroup administrators|:|net user|""|or|and";
        private const string StrRegex = @"[-|;|,|/|(|)|[|]|}|{|%|@|*|!|']";

        /// <summary>
        /// 另一种检查字符串是否包含SQL关键字的方法
        /// </summary>
        /// <param name="contents"></param>
        /// <returns>true:含有非法字符，false:被测字符串是个安全的字符串</returns>
        public static bool HasKeywords(string contents)
        {
            bool bReturnValue = false;
            if (contents.Length > 0)
            {
                string sLowerStr = contents.ToLower();
                string sRxStr = @"(\sand\s)|(\sand\s)|(\slike\s)|(select\s)|(insert\s)|(delete\s)|(update\s[\s\S].*\sset)|(create\s)|(\stable)|(<[iframe|/iframe|script|/script])|(')|(\sexec)|(declare)|(\struncate)|(\smaster)|(\sbackup)|(\smid)|(\scount)|(cast)|(%)|(\sadd\s)|(\salter\s)|(\sdrop\s)|(\sfrom\s)|(\struncate\s)|(\sxp_cmdshell\s)";
                Regex sRx = new Regex(sRxStr);
                bReturnValue = sRx.IsMatch(sLowerStr, 0);
            }
            return bReturnValue;
        }
    }
}
